//
//  CustomTableViewCell.m
//  StickyDemo
//
//  Created by kckj on 2021/7/5.
//

#import "CustomTableViewCell.h"

@interface CustomTableViewCell ()<UIScrollViewDelegate>
@property (weak, nonatomic) IBOutlet UIButton *oneButton;
@property (weak, nonatomic) IBOutlet UIButton *twoButton;
@property (weak, nonatomic) IBOutlet UIButton *thereButton;

@property (nonatomic, strong) NSArray *buttons;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *lineViewCenter;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *contentViewWidth;

@property (weak, nonatomic) IBOutlet UIView *scrollviewContentView;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@end

@implementation CustomTableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];
    // Initialization code
    [self setBackgroundColor:[UIColor blackColor]];
    self.buttons = @[self.oneButton,self.twoButton,self.thereButton];
    self.oneButton.tag = 100;
    self.twoButton.tag = 101;
    self.thereButton.tag = 102;
    self.oneButton.selected = YES;
    self.contentViewWidth.constant = [UIScreen mainScreen].bounds.size.width * 3.0f;
    self.scrollView.delegate = self;
}
- (IBAction)buttonAction:(UIButton *)sender {
    for (UIButton *button in self.buttons) {
        [button setSelected:NO];
    }
    sender.selected = YES;
    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
    NSInteger index = (sender.tag - 100);
    [self.scrollView setContentOffset:CGPointMake(index * screenWidth, 0) animated:YES];
}
#pragma mark - ScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat offX = scrollView.contentOffset.x;
    CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;
    CGFloat width = ([UIScreen mainScreen].bounds.size.width - 32) / 3.0f;
    self.lineViewCenter.constant = width / screenWidth * offX;
}
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    NSInteger index = scrollView.contentOffset.x / width;
    for (int i = 0; i < self.buttons.count; i ++) {
        UIButton *button = self.buttons[i];
        if (i == index) {
            button.selected = YES;
        } else {
            button.selected = NO;
        }
    }
}
- (void)cellScrollViewAddChildViews:(NSArray<UIViewController *> *)viewControllers {
    CGFloat width = [UIScreen mainScreen].bounds.size.width;
    for (int i = 0; i < viewControllers.count; i ++) {
        UIViewController *vc = [viewControllers objectAtIndex:i];
        vc.view.frame = CGRectMake(i * width, 0, CGRectGetWidth(self.scrollView.frame), CGRectGetHeight(self.scrollView.frame));
        [self.scrollView addSubview:vc.view];
    }
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end
